package com.glsc.ngateway.shortmsg.service;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpSearchDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.common.api.shortmsg.bo.*;
import com.glsc.ngateway.common.base.domain.mysql.gateway.shortmsg.MessageWeixinGroup;
import com.glsc.ngateway.common.base.domain.mysql.gateway.shortmsg.NoticeMessageSend;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.shortmsg.MessageWeixinGroupRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.shortmsg.NoticeMessageSendRepository;
import com.glsc.ngateway.common.base.utils.MyEmojiTool;
import com.glsc.ngateway.common.base.utils.NGSMDateTimeFormatter;
import com.glsc.ngateway.shortmsg.constant.ShortmsgConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class ShortMessageService {

    private static final Logger logger = LoggerFactory.getLogger(ShortMessageService.class);

    @Resource
    private NoticeMessageSendRepository noticeMessageSendRepository;
    @Resource
    private IFeignLdapService iFeignLdapService;
    @Resource
    private MessageWeixinGroupRepository messageWeixinGroupRepository;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${weixin.url}")
    public String url;
    @Value("${weixin.corpid}")
    public String corpid;
    @Value("${weixin.corpsecret}")
    public String corpsecret;
    @Value("${weixin.sendurl}")
    public String sendurl;
    @Value("${weixin.agentid}")
    public String agentid;

    @Value("${weixin.useridurl}")
    public String useridurl;
    @Value("${weixin.roboturl}")
    public String roboturl;
    @Value("${weixin.send-agent-message-generic}")
    public String agentUrl;
    @Value("${weixin.send-group-robot-message}")
    public String robotUrl;

    public String initDbrec(String mobile, String content, String sysid, String remoteAddr) {
        logger.info("将短信发送记录入库");
        NoticeMessageSend sendMsg = new NoticeMessageSend();
        sendMsg.setTelephone(mobile);
        sendMsg.setContent(content);
        sendMsg.setSysid(sysid);
        sendMsg.setOpState(remoteAddr);
        sendMsg.setMessageId(mobile + "-" + LocalDateTime.now().format(NGSMDateTimeFormatter.df_dttm) + "-" + ((int) (Math.random() * 1000)));
        noticeMessageSendRepository.save(sendMsg);
        logger.info("入库成功,结果为:{}", sendMsg.getId());
        return sendMsg.getMessageId();
    }

    public List<NoticeMessageSend> findByMessageId(String msgId) {
        return noticeMessageSendRepository.findBymessageId(msgId);
    }

    public String getAccessToken() {

        try {
            ResponseEntity<String> getForEntity = restTemplate.getForEntity(url + "?corpid=" + corpid + "&corpsecret=" + corpsecret, String.class);
            logger.info("企业微信接口getAccessToken返回原始报文:" + getForEntity.getBody());
            if ((HttpStatus.OK).equals(getForEntity.getStatusCode())) {
                String res = getForEntity.getBody();
                JSONObject json = JSONObject.parseObject(res);
                if ("0".equals(json.getString("errcode"))) {
                    String token = json.getString("access_token");
                    String second = json.getString("expires_in");
                    logger.info("企业微信接口获取token:" + token + ",过期时间秒:" + second);
                    redisTemplate.opsForValue().set(ShortmsgConstant.REDIS_WEIXIN_TOKEN, token, Integer.parseInt(second), TimeUnit.SECONDS);
                    return token;
                }
            }
            return null;
        } catch (Exception e) {
            logger.error("企业微信接口获取token异常，请查看。", e);
            throw new RuntimeException("企业微信接口获取token异常，请查看。");
        }
    }


    public String getUserIdByMobile(String badge, String mobile, String token) {

        try {
            if (StringUtils.isEmpty(mobile)) {
                return null;
            }
            WeixinUseridRequest request = new WeixinUseridRequest();
            request.setMobile(mobile);
            String strrequest = JSONObject.toJSONString(request);
            JSONObject json = JSONObject.parseObject(strrequest);
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(useridurl + token, json, String.class);
            logger.info("企业微信接口getUserIdByMobile返回原始报文:" + postForEntity.getBody());
            if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                String body = postForEntity.getBody();
                JSONObject res = JSONObject.parseObject(body);
                if ("0".equals(res.getString("errcode"))) {
                    String userid = res.getString("userid");
                    logger.info("企业微信接口获取userid:" + userid + ",手机号:" + mobile);
                    LdapResponse<List<LdapEhrEmpDto>> resp = iFeignLdapService.getUserList(LdapEhrEmpSearchDto.builder().mobile(mobile).badge(badge).build());
                    resp.getData().forEach(e->{
                        e.setOaUserId(Integer.valueOf(userid));
                    });
                    iFeignLdapService.save(resp.getData());
                    return userid;
                }
            }
            return null;
        } catch (Exception e) {
            logger.error("企业微信接口getUserIdByMobile异常，请查看。", e);
            throw new RuntimeException("企业微信接口getUserIdByMobile异常，请查看。");
        }
    }

    public String sendWeixinMessage(WeixinMsgRequest request, String token) {

        try {
            List<String> badges = Arrays.asList(request.getTouser().split("\\|"));
            LdapResponse<List<LdapEhrEmpDto>> resp = iFeignLdapService.getUserList(LdapEhrEmpSearchDto.builder().badgeList(badges).build());
            Map<String, LdapEhrEmpDto> map = Objects.isNull(resp) || CollectionUtils.isEmpty(resp.getData()) ? Collections.EMPTY_MAP :
                    resp.getData().stream().collect(Collectors.toMap(LdapEhrEmpDto::getBadge, o -> o));
            StringBuffer sb = new StringBuffer();
            badges.forEach(badge -> {
                String userid = null;
                if (map.containsKey(badge)) {
                    LdapEhrEmpDto emp = map.get(badge);
                    userid = Objects.nonNull(emp.getOaUserId()) ? String.valueOf(emp.getOaUserId()) : getUserIdByMobile(emp.getBadge(), emp.getMobile(), token);
                }
                if (StringUtils.isEmpty(userid)) {
                    logger.error("企业微信接口发送，未取到userid。" + badge);
                } else {
                    sb.append(userid).append("|");
                }
            });

            if (sb == null || sb.length() == 0) {
                logger.error("企业微信接口发送，所有都未取到userid。" + request.getTouser());
                throw new RuntimeException("企业微信接口发送异常，请查看。");
            }
            request.setTouser(sb.deleteCharAt(sb.length() - 1).toString());
            request.setAgentid(Integer.parseInt(agentid));
            String strrequest = JSONObject.toJSONString(request);
            JSONObject json = JSONObject.parseObject(strrequest);
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(sendurl + token, json, String.class);
            logger.info("企业微信接口sendWeixinMessage返回原始报文:" + postForEntity.getBody());
            if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                String res = postForEntity.getBody();
                JSONObject resjson = JSONObject.parseObject(res);
                if ("0".equals(resjson.getString("errcode"))) {
                    logger.info("企业微信接口sendWeixinMessage发送成功。badges=" + badges.toString() + ",msgid=" + resjson.getString("msgid"));
                    return resjson.getString("msgid");
                }
            }
            logger.error("企业微信接口sendWeixinMessage发送失败！报文:" + postForEntity.getBody());
            return null;
        } catch (Exception e) {
            logger.error("企业微信接口获取token异常，请查看。", e);
            throw new RuntimeException("企业微信接口获取token异常，请查看。");
        }
    }

    public String sendRobotMessage(WeixinRobotRequest request, String token) {

        try {
            String strrequest = JSONObject.toJSONString(request);
            JSONObject json = JSONObject.parseObject(strrequest);

            if (StringUtils.isEmpty(request.getTogroup())) {
                logger.error("企业微信接口sendRobotMessage发送失败,togroup为空！");
                return null;
            }
            MessageWeixinGroup group = messageWeixinGroupRepository.findByGroupName(request.getTogroup());
            if (group == null) {
                logger.error("企业微信接口sendRobotMessage发送失败,未找到该group！" + request.getTogroup());
                return null;
            }
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(roboturl + group.getGroupKey(), json, String.class);
            logger.info("企业微信接口sendRobotMessage返回原始报文:" + postForEntity.getBody());
            if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                String res = postForEntity.getBody();
                JSONObject resjson = JSONObject.parseObject(res);
                if ("0".equals(resjson.getString("errcode"))) {
                    logger.info("企业微信接口sendRobotMessage发送成功。");
                    return "ok";
                }
            }
            logger.error("企业微信接口sendRobotMessage发送失败！报文:" + postForEntity.getBody());
            return null;
        } catch (Exception e) {
            logger.error("企业微信接口获取token异常，请查看。", e);
            throw new RuntimeException("企业微信接口获取token异常，请查看。");
        }
    }

    /*企微应用消息发送
     * 发送示例：
     【文本类型精简发送示例1】
     {
     "oaUserAccounts":["weizt","zzp"],
     "agentId":"1000071",
     "textContent":"content":"测试微信发送"
     }

     【示例2】
     {
     "oaUserAccounts":[
     "weizt"
     ],
     "msgType":"text",
     "agentId":"1000071",
     "text":{
     "content":"测试微信发送"
     }
     }
     * 企业微信消息接口说明：https://developer.work.weixin.qq.com/document/path/90236
     * @return
     */
    public String sendAgentMessageGeneric(MessageGenericVo messageGenericVo) throws InterruptedException {
        if (StrUtil.isEmpty(messageGenericVo.getAgentId())) {
            throw PlatformException.error("请求企微推送消息，应用agentId不能为空");
        }
        if (StrUtil.isEmpty(messageGenericVo.getMsgType())) {
            messageGenericVo.setMsgType("text");
        }
        if (messageGenericVo.getAdditionalProperties() == null) {//附加消息内容
            messageGenericVo.setAdditionalProperties(new HashMap<>());
        }

        if (StrUtil.isNotEmpty(messageGenericVo.getTextContent())) {//文本消息发送
            messageGenericVo.setMsgType("text");
            if (messageGenericVo.getAdditionalProperties().get("text") == null) {
                messageGenericVo.getAdditionalProperties().put("text", new HashMap<>());
            }

            HashMap textMap = (HashMap) messageGenericVo.getAdditionalProperties().get("text");
            textMap.put("content", messageGenericVo.getTextContent());
        }

        /**
         * 支持重复消息检查，当指定 "enable_duplicate_check": 1开启: 表示在一定时间间隔内，同样内容（请求json）的消息，不会重复收到；
         * 时间间隔可通过duplicate_check_interval指定，默认1800秒。
         * */
        if (messageGenericVo.getAdditionalProperties().get("safe") == null) {
            messageGenericVo.getAdditionalProperties().put("safe", 0);
        }
        if (messageGenericVo.getAdditionalProperties().get("enable_id_trans") == null) {
            messageGenericVo.getAdditionalProperties().put("enable_id_trans", 0);
        }
        if (messageGenericVo.getAdditionalProperties().get("duplicate_check_interval") == null) {//半个小时内不重复
            messageGenericVo.getAdditionalProperties().put("duplicate_check_interval", 1800);
        }

        //超长文本内容检测，超过2048字节自动拆分
        int splitByteLength = 1960;//实际微信限制2048字节，因需要显示："消息过长拆分，总共XX条，第XX条"提示，所以限制为1960字节。
        List<String> textContentList = new ArrayList<>();


        if ("text".equals(messageGenericVo.getMsgType())) {
            String contentInitialString = ((HashMap) messageGenericVo.getAdditionalProperties().get("text")).get("content").toString();
            textContentList = MyEmojiTool.stringSplitByByteLength(contentInitialString, splitByteLength);
        }

        //TODO picurl等超过2048字节处理

        String retMsg = null;
        int sendMsgCnt = 0;
        do {

            if (textContentList.size() > 0) {//如果是text，则自动拆分多条发送
                if (textContentList.size() == 1) {
                    ((HashMap) messageGenericVo.getAdditionalProperties().get("text")).put("content", textContentList.get(sendMsgCnt));
                } else {
                    String splitMsgInfo = String.format("消息过长拆分，总共%s条，第%s条：", textContentList.size(), (sendMsgCnt + 1));
                    ((HashMap) messageGenericVo.getAdditionalProperties().get("text")).put("content", splitMsgInfo + textContentList.get(sendMsgCnt));
                }
            } else {//非text类型，也只发送一次即可
                logger.info("非text消息发送开始处理");
            }
            sendMsgCnt++;
            if (sendMsgCnt > 1) {//多条发送时，企微消息异步发送，为解决多条先发送后抵达，这里sleep休眠200毫秒
                Thread.sleep(200);
            }
            try {
                ResponseEntity<String> postForEntity = restTemplate.postForEntity(agentUrl, messageGenericVo, String.class);
                logger.info("企业微信接口sendAgentMessageGeneric返回原始报文:" + postForEntity.getBody());
                if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                    String res = postForEntity.getBody();
                    JSONObject resjson = JSONObject.parseObject(res);
                    logger.info(messageGenericVo + "sendReturn" + resjson);
                    retMsg = resjson.toJSONString();
//                if ("0".equals(resjson.getString("code"))) {
//                    logger.info("企业微信接口sendAgentMessageGeneric发送成功。");
//                    return "ok";
//                }
                }
                logger.info("企业微信接口sendAgentMessageGeneric发送返回报文:" + postForEntity.getBody());
            } catch (Exception e) {
                logger.info("企业微信接口sendAgentMessageGeneric异常，请查看。", e);
                throw new RuntimeException("企业微信接口sendAgentMessageGeneric异常，请查看。");
            }

        } while (sendMsgCnt < textContentList.size());//如果text多条，则分多次发送
        return retMsg;
    }

    /**
     {
     "webhookUrl": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=aeefc836-1142-437e-8f40-5268ea331634",
     "msgType": "image",
     "image": {
     "base64": "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",
     "md5": "a95b1f2dfe65c87e1ff7efed42bfab52"
     }
     }
     * @param webhookGenericVo
     * @return
     */
    public String sendGroupRobotMessage(WebhookGenericVo webhookGenericVo) {
        try {
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(robotUrl, webhookGenericVo, String.class);
            logger.info("企业微信接口sendGroupRobotMessage返回原始报文:" + postForEntity.getBody());
            if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                String res = postForEntity.getBody();
                JSONObject resjson = JSONObject.parseObject(res);
                logger.info(webhookGenericVo+"sendReturn"+resjson);
                return resjson.toJSONString();
//                if ("0".equals(resjson.getString("code"))) {
//                    logger.info("企业微信接口sendGroupRobotMessage发送成功。");
//                    return "ok";
//                }
            }
            logger.error("企业微信接口sendGroupRobotMessage发送失败！报文:" + postForEntity.getBody());
            return null;
        } catch (Exception e) {
            logger.error("企业微信接口sendGroupRobotMessage异常，请查看。", e);
            throw new RuntimeException("企业微信接口sendGroupRobotMessage异常，请查看。");
        }
    }

//    public void sendShortMessage(String message) {
//
//
//        Map<String, Object> map = JSON.parseObject(message,Map.class);
//
//        String returnMessage = restTemplate.postForObject(gatewayConstant.SHORT_MESSAGE_URL,map,String.class);
//
//        logger.info("发送短信结果为：" + returnMessage);
//        Integer returnFlag = judgeMessageResult(returnMessage);
//
//
//        Map paramMap = (Map) map.get("param");
//
//
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_1){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.FAILURE,Boolean.FALSE);  //
//
//            logger.error("短信HTTP 转发接口错误,短线接收人为：" +paramMap.get("mobile_tel").toString() + ",短信内容为：" + paramMap.get("notice_content").toString() +",错误消息为：" + returnMessage);
//        }
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_2){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.FAILURE,Boolean.FALSE);  //
//            logger.error("短信平台错误,短线接收人为：" +paramMap.get("mobile_tel").toString() + ",短信内容为：" + paramMap.get("notice_content").toString() +",错误消息为：" + returnMessage);
//        }
//        if(returnFlag== ExceptionConstant.SHORT_MESSAGE_RESULT_COR){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.SUCCESS,Boolean.TRUE);  //
//        }
//
//    }


//
//
//    @Override
//    public void sendShortMessage(String message) {
//
//
//        Map<String, Object> map = JSON.parseObject(message,Map.class);
//
//        String returnMessage = restTemplate.postForObject(gatewayConstant.SHORT_MESSAGE_URL,map,String.class);
//
//        logger.info("发送短信结果为：" + returnMessage);
//        Integer returnFlag = judgeMessageResult(returnMessage);
//
//
//        Map paramMap = (Map) map.get("param");
//
//
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_1){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.FAILURE,Boolean.FALSE);  //
//
//            logger.error("短信HTTP 转发接口错误,短线接收人为：" +paramMap.get("mobile_tel").toString() + ",短信内容为：" + paramMap.get("notice_content").toString() +",错误消息为：" + returnMessage);
//        }
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_2){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.FAILURE,Boolean.FALSE);  //
//            logger.error("短信平台错误,短线接收人为：" +paramMap.get("mobile_tel").toString() + ",短信内容为：" + paramMap.get("notice_content").toString() +",错误消息为：" + returnMessage);
//        }
//        if(returnFlag== ExceptionConstant.SHORT_MESSAGE_RESULT_COR){
//            insertAndUpdateMessageInfo(paramMap.get("notice_content").toString(),paramMap.get("mobile_tel").toString(),paramMap.get("op_station").toString(),GatewayConstant.SUCCESS,Boolean.TRUE);  //
//        }
//
//    }
//
//
//
//    @Override
//    public Map<String,String> analysisMessageResult(String messageResult) {
//
//        JSONObject rowData = JSONObject.parseObject(messageResult);
//        JSONObject jsonObject = rowData.getJSONObject("data").getJSONObject("datasets").getJSONArray("dataset0").getJSONObject(0);
//        Map<String,String> map = new HashMap<String,String> ();
//        map.put("code", jsonObject.getString("error_no"));
//        map.put("message", jsonObject.getString("error_info"));
//        return map;
//    }
//
//
//
//
//
//    @Override
//    public Map<String,String> dealShortMessage(String content, String mobile, String opStation) {
//
//        String returnMessage = sendShortMessage(content,mobile,opStation);
//        Integer returnFlag = judgeMessageResult(returnMessage);
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_1){
//            throw new BusinessException(ExceptionConstant.BussinessException,"短信HTTP 转发接口错误，错误消息为：" + returnMessage);
//        }
//        if(returnFlag==ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_2){
//            throw new BusinessException(ExceptionConstant.BussinessException,"短信平台错误，错误消息为：" + returnMessage);
//        }
//        Map<String,String> dataMap = analysisMessageResult(returnMessage);
//        return dataMap;
//    }
//
//    @Override
//    public Integer judgeMessageResult(String messageResult) {
//
//        Integer flag =  ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_1; // 默认为短信HTTP服务台不能正确提供服务。
//        JSONObject rowData = JSONObject.parseObject(messageResult);
//        if(rowData.containsKey("data")&&rowData.containsKey("code")){
//            String code = rowData.getString("code");
//            if(code.equals("20000")){
//                String errorNo =rowData.getJSONObject("data").getString("errorno");
//                if(errorNo.equals("0")){
//                    flag = ExceptionConstant.SHORT_MESSAGE_RESULT_COR;
//                }else{
//                    flag = ExceptionConstant.SHORT_MESSAGE_RESULT_EXC_2;
//                }
//            }
//        }
//        return flag;
//    }
//
//    @Override
//    public Integer insertAndUpdateMessageInfo(String content, String mobile, String opStation, String sendStatus, Boolean isUpdate) {
//
//        Integer result = 0;
//        NoticeMessageSend nms = new NoticeMessageSend(mobile,GatewayConstant.MESSAGE_BIZ_CODE,opStation,sendStatus,content);
//        if(!isUpdate){
//            result = nmsMapper.insert(nms);
//        }
//        if(result<=0){
//            logger.error("写数据库失败："+nms.toString());
//        }
//
//        return 0;
//    }
//
//
//    @Override
//    public List<NoticeMessageSend> getMessageInfo(String messageId) {
//
//        return nmsMapper.getMessageInfo(messageId);
//    }
}
